<?php
require("setup.php");
//获取验证码
c("Get login form data");

$client = new GuzzleHttp\Client();
$jar    = new \GuzzleHttp\Cookie\CookieJar;

$form_url = "http://www.douban.com/";
$res      = $client->request('GET', $form_url);
$str      = $res->getBody();

$is_need_check = false;
if (strpos($str, "captcha") !== false) {
    $is_need_check = true;
    preg_match_all("/<input.*?name=\"captcha\-id\".*?value=\"(.*?)\"\/>/is", $str, $array_info);
    $captcha_id = $array_info[1][0];

    $img_url     = "http://www.douban.com/misc/captcha?id=" . $captcha_id . "&size=s";
    $res         = $client->request('GET', $img_url, ['cookies' => $jar]);
    $img_content = $res->getBody();
    file_put_contents("captcha_id.jpg", $img_content);

    //输入图片
    $fh = fopen('php://stdin', 'r');
    echo "Need code:";
    $captcha_code = trim(fread($fh, 1000));
    fclose($fh);
}


////开始登录
c("Start Login!");

$login_url                  = "https://www.douban.com/accounts/login";
$post_data                  = array();
$post_data['form_email']    = "sunny_lrj@yeah.net";
$post_data['form_password'] = "123asd123";
$post_data['redir']         = "http://www.douban.com/group/";
$post_data['source']        = "group";
$post_data['user_login']    = "登录";
$post_data['remember']      = "on";
if ($is_need_check == true) {
    $post_data['captcha-id']       = $captcha_id;
    $post_data['captcha-solution'] = $captcha_code;
}
//#print_r($post_data);exit;
$res = $client->request('POST', $login_url, ["form_params" => $post_data, 'cookies' => $jar]);
$str = $res->getBody();
if (strpos($str, "我的小组话题") == true) {
    c("Login success!");
    if (is_file("captcha_id.jpg")) {
        unlink("captcha_id.jpg");
    }
} else {
    c("Login fail,Please relogin");
}

